import { Ab_AudioManager_bA } from "../../src/manager/audio-manager";
import { Ab_DataTransfer_bA } from "../A-LIB/lib.b.data";
import { Ab_APP_NAME_bA } from "../frame.config";
import Ab_get_proxy_clock_bA from "./data.global.clock";
import Ab_get_proxy_trigger_bA from "./data.global.trigger";

export default class Ab_GlobalDC_bA {
	private static Ab__trigger__bA: ReturnType<typeof Ab_get_proxy_trigger_bA>;
	private static Ab__clock__bA: ReturnType<typeof Ab_get_proxy_clock_bA>;

	public static get Ab_Trigger_bA(){
		return Ab_GlobalDC_bA.Ab__trigger__bA;
	}
	public static get Ab_Clock_bA(){
		return Ab_GlobalDC_bA.Ab__clock__bA;
	}

	public static Ab_init_bA(){
		Ab_GlobalDC_bA.Ab__trigger__bA = Ab_get_proxy_trigger_bA('global_trigger');
		Ab_GlobalDC_bA.Ab__clock__bA = Ab_get_proxy_clock_bA('global_clock', Ab_APP_NAME_bA);
		Ab_GlobalDC_bA.Ab_clockRun_bA();
		Ab_GlobalDC_bA.Ab_listening_bA();
	}

	private static Ab_listening_bA(){
		Ab_DataTransfer_bA.Ab_follow_bA(Ab_GlobalDC_bA.Ab_Trigger_bA, 'Ab_CLICK_bA', (o, v)=>{
			Ab_AudioManager_bA.Ab_playEffect_bA(Ab_AudioManager_bA.Ab_EAudio_bA.Ab_EF_CLICK_bA);
		}, false);
		let interval_stamp = Date.now();
		let td = 0;
		Ab_DataTransfer_bA.Ab_follow_bA(Ab_GlobalDC_bA.Ab_Clock_bA, 'Ab_current_time_bA', (o, v)=>{
			td = v - interval_stamp;
			interval_stamp = v;
			Ab_GlobalDC_bA.Ab__interval_call_token_map__bA.forEach(async item=>{
				if((v - item.timestamp) >= item.interval){
					item.timestamp += item.interval;
					Reflect.apply(item.call, item.that, [td, v]);
				}
			});
		}, false);

		Ab_GlobalDC_bA.Ab_interval_bA(60 * 1000, (td, now)=>{
			if(abi.Ab_time_bA.Ab_sameDay_bA(Ab_GlobalDC_bA.Ab_Clock_bA.Ab_login_time_bA, now)) return void 0;

			Ab_GlobalDC_bA.Ab_Clock_bA.Ab_login_time_bA = now;
			Ab_GlobalDC_bA.Ab_Trigger_bA.Ab_NEW_DAY_bA = now;
		});
	}

	private static Ab_clockRun_bA(){

		let now = Date.now();
		if(!abi.Ab_time_bA.Ab_sameDay_bA(Ab_GlobalDC_bA.Ab_Clock_bA.Ab_login_time_bA, now)){
			Ab_GlobalDC_bA.Ab_Clock_bA.Ab_login_time_bA = now;
			Ab_GlobalDC_bA.Ab_Trigger_bA.Ab_NEW_DAY_bA = now;
		}

		setInterval(()=>Ab_GlobalDC_bA.Ab_Clock_bA.Ab_current_time_bA = Date.now(), 1000/30);
	}

	private static Ab__interval_call_token_map__bA: Map<string, {timestamp: number, interval: number, call: (td: number, now: number)=>any, that?: any}> = new Map();

	public static Ab_interval_bA(interval: number, call: (td: number, now: number)=>any, thisArg?: any){
		let token = abi.Ab_string_bA.Ab_randomToken_bA(7, 36, tlkn=>!Ab_GlobalDC_bA.Ab__interval_call_token_map__bA.has(tlkn));
		Ab_GlobalDC_bA.Ab__interval_call_token_map__bA.set(token, {timestamp: Date.now(), interval, call, that: thisArg??null})
		return token;
	}

	public static Ab_clearInterval_bA(token: string){
		if(!Ab_GlobalDC_bA.Ab__interval_call_token_map__bA.has(token)) return void 0;

		Ab_GlobalDC_bA.Ab__interval_call_token_map__bA.delete(token);
	}
}
